package org.myspringframework.aop.framework.adapter;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.myspringframework.aop.Advisor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

//适配器注册器，负责使用advisorAdapter适配器将advisor中advice通知统一转换为methodInterceptor
public class DefaultAdvisorAdapterRegistry {
    //todo:这里我只添加了MethodBeforeAdviceAdapter，还有AfterReturningAdviceAdapter，ThrowsAdviceAdapter
    private final List<AdvisorAdapter> adapters = new ArrayList(1);

    public DefaultAdvisorAdapterRegistry() {
        this.adapters.add(new MethodBeforeAdviceAdapter());
        /*this.registerAdvisorAdapter(new AfterReturningAdviceAdapter());
        this.registerAdvisorAdapter(new ThrowsAdviceAdapter());*/
    }

    //转换advisor，获取将advice统一转换为methodInterceptor后的MethodInterceptor数组
    public MethodInterceptor[] getInterceptors(Advisor advisor) throws Exception {
        List<MethodInterceptor> interceptors = new ArrayList();
        Advice advice = advisor.getAdvice();

        if (advice instanceof MethodInterceptor) {
            //无需转换
            interceptors.add((MethodInterceptor)advice);
        }else{

            Iterator iterator = this.adapters.iterator();
            //迭代遍历adapter进行转换
            while(iterator.hasNext()) {
                AdvisorAdapter adapter = (AdvisorAdapter)iterator.next();
                if (adapter.supportsAdvice(advice)) {
                    interceptors.add(adapter.getInterceptor(advisor));
                }
            }
        }


        if (interceptors.isEmpty()) {
            throw new Exception("转换methodInterceptor失败");
        } else {
            return (MethodInterceptor[])interceptors.toArray(new MethodInterceptor[0]);
        }
    }
}
